package cn.jly.springboot24.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 1. 编写一个拦截器，实现HandlerInterceptor接口
 * 2. 在WebMvcConfig中注册拦截器，如果是拦截所有，要放行一些特定请求，比如登录和静态资源等
 *
 * @PackageName cn.jly.springboot24.interceptor
 * @ClassName LogHandlerInterceptor
 * @Description 自定义日志拦截器
 * @Author 姬岚洋
 * @Date 2021/1/17 下午 6:12
 */
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LogHandlerInterceptor.preHandle 请求的url -> {}", request.getRequestURI());

        final HttpSession session = request.getSession();
        final Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null) {
            // 放行
            return true;
        }

        // 拦截，没有登录，跳转到登录页
        // request.setAttribute("msg", "清先登录");
        // request.getRequestDispatcher("/login").forward(request, response);
        response.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("LogHandlerInterceptor.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("LogHandlerInterceptor.afterCompletion");
    }
}
